package com.pine.manager.pineframework.trigger.impl;

import com.pine.common.beans.exception.BusinessException;
import com.pine.common.beans.exception.ExceptionCodeEnum;
import com.pine.common.beans.pineframework.request.SysApprovalApplicationSaveOrUpdateRequest;
import com.pine.common.trigger.TriggerContext;
import com.pine.manager.core.TriggerTypeEnum;
import com.pine.manager.pineframework.bo.SysApprovalApplicationBo;
import com.pine.manager.pineframework.query.SysApprovalApplicationQuery;
import com.pine.manager.pineframework.trigger.AbstractTriggerTemplateAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * <p>
 * 系统审批申请表新增或修改数据 触发器
 * </p>
 *
 * @author pine manage
 * @since 2024-11-05
 */
@Component
@Slf4j
public class SysApprovalApplicationSaveOrUpdateTrigger extends AbstractTriggerTemplateAdapter<SysApprovalApplicationSaveOrUpdateRequest, Boolean> {

    private boolean isSave;

    private SysApprovalApplicationBo oldSysApprovalApplicationBo;

    public SysApprovalApplicationSaveOrUpdateTrigger() {
        super(TriggerTypeEnum.SYS_APPROVAL_SAVE_OR_UPDATE);
    }

    @Override
    protected void before(TriggerContext<SysApprovalApplicationSaveOrUpdateRequest> triggerContext) {
        SysApprovalApplicationSaveOrUpdateRequest request = triggerContext.getTriggerRequest();
        isSave = Objects.isNull(request.getId());

        // 尝试查询旧的审批申请
        SysApprovalApplicationQuery query = new SysApprovalApplicationQuery();
        query.setId(request.getId());
        oldSysApprovalApplicationBo = sysApprovalApplicationManager.getOne(query);

        // 校验
        if (isSave) {
            checkOnSave();
        } else {
            checkOnUpdate();
        }
    }

    /**
     * 触发
     *
     * @param triggerContext 触发上下文
     * @return 触发结果
     */
    @Override
    public Boolean trigger(TriggerContext<SysApprovalApplicationSaveOrUpdateRequest> triggerContext) {
        // todo 待完善
        return false;
    }

    private void checkOnSave() {
        // 校验审批申请是否重复
        if (Objects.nonNull(oldSysApprovalApplicationBo)) {
            throw new BusinessException(ExceptionCodeEnum.APPROVAL_APPLICATION_EXIST);
        }
    }

    private void checkOnUpdate() {
        // 校验审批申请是否存在
        if (Objects.isNull(oldSysApprovalApplicationBo)) {
            throw new BusinessException(ExceptionCodeEnum.APPROVAL_APPLICATION_NOT_EXIST);
        }
    }
}
